package com.yudi.blog.bussiness.controller.admin;

import com.yudi.blog.bussiness.dto.Type;
import com.yudi.blog.bussiness.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @Author YuDi
 * @Date 2021/11/10 16:23
 * @Version 1.0
 */
@Controller
@RequestMapping("/admin")
public class TypesController {

    @Autowired
    TypeService typeService;


    @GetMapping("/types")
    public String types(@PageableDefault(size = 5, sort = {"id"}, direction = Sort.Direction.DESC)Pageable pageable,
                        Model model){
        model.addAttribute("page", typeService.listType(pageable));
        return "admin/types";
    }


    @GetMapping("/types/input")
    public String typesInput(Model model){

        model.addAttribute("tag", new Type());
        return "admin/types-input";
    }


    @GetMapping("/types/input/{id}")
    public String editInput(@PathVariable Long id, Model model){
        model.addAttribute("tag", typeService.getType(id));
        return "/admin/types-input";
    }


    @PostMapping("/types")
    public String typeSave(Type type, RedirectAttributes redirectAttributes){
        Type t = typeService.saveType(type);

        if(t == null){
            redirectAttributes.addFlashAttribute("message", "添加失败");
        } else {
            redirectAttributes.addFlashAttribute("message", "添加成功");
        }
        return "redirect:/admin/types";
    }


    @PostMapping("/types/input/{id}")
    public String update(@PathVariable Long id, Type type, RedirectAttributes redirectAttributes){

        if("".equals(type.getName())){
            return "admin/types-input";
        }
        Type t = typeService.updateType(id, type);

        if(t != null){
            redirectAttributes.addFlashAttribute("message", "分类更新成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "分类更新失败");
        }
        return "redirect:/admin/types";
    }


    @GetMapping("types/delete/{id}")
    public String delete(@PathVariable Long id, RedirectAttributes redirectAttributes){
        typeService.deleteType(id);
        redirectAttributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/types";
    }

}
